package LogServer.dao

import LogServer.constants.PropertiesMongo
import LogServer.utils.DateUtil
import com.mongodb.DBCollection
import com.mongodb.casbah.commons.{Imports, MongoDBObject}

import scala.collection.mutable.ArrayBuffer

/**
  * Created by root on 17-2-21.
  */
object Demo {
  /**
    *
    * @param iterator
    */
  def saveToDb(iterator: Iterator[String],propertiesMongoObject: PropertiesMongo): Unit ={
    //Convert Iterator to String
    val sb = new StringBuilder()
    println("----------------------")
    iterator.foreach(i => sb.append(i))
    val str = sb.toString()
    println(str)

    val time_regex = """\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2},\d{3}""".r
    val match_iterator = time_regex.findAllIn(str)
    val indexArray = ArrayBuffer[Int]()
    for (elem <- match_iterator) {
      val index = str.indexOf(elem)
      indexArray += index
    }
    //    indexArray.foreach(i => println(i))
    val strArray = ArrayBuffer[String]()

    try {
      for(i <- 0 until indexArray.length){
        val j = i + 1
        if(j < indexArray.length){
          strArray += str.substring(indexArray(i),indexArray(j))
        }else{
          //only one elemet in strArray
          strArray += str.substring(indexArray(i))
        }
      }
    } catch {
      case ex: Exception => // Handle other I/O error
    }
    //    strArray.foreach(i => println(i))
    println(str)

    val tempArray = ArrayBuffer[String]()
    for (elem <- strArray) {
      val dataArray = elem.split(" - ")
      val time = dataArray(0).split(",")(0)
      val file = dataArray(1)
      val logLevel = dataArray(2)
      val result = dataArray(3)
      //      println("time:"+time+" file:"+file+" logLevel:"+logLevel+" result:"+result)
      tempArray += file
    }
    val countTuple = ArrayBuffer[Tuple2[String,Int]]()
    val tempSet = tempArray.toSet
    for(i <- tempSet){
      var count = 0
      for(j <- 0 until tempArray.length){
        if(i.equals(tempArray(j))){
          count += 1
        }
      }
      countTuple += new Tuple2(i,count)
    }
    println(countTuple)
    println("----------------------")

    var files =  ArrayBuffer[String]()
    var counts =  ArrayBuffer[Int]()
    countTuple.foreach(i =>{
      files += i._1
      counts += i._2
    })

    val time = DateUtil.getCurrent_time()
    //Mongo DBObject
    val dBObject: Imports.DBObject = MongoDBObject("time"->time,
      "file"->files.toArray,"count"->counts.toArray)
    //Use Collection
    val coll = MongoConnector.getConnection(propertiesMongoObject,"vmhost")
    coll.save(dBObject)
//    update(coll,str)
  }

  def update(coll: DBCollection,str: String): Unit ={
//    val obj = coll.findAndModify(MongoDBObject("_id"->str),MongoDBObject("test"->"ttttt"))
    println(str)
    val obj = coll.findOne(MongoDBObject("_id"->str))
    println(obj)
  }
}
